package com.lfs.market.job;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lfs.market.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author lfs
 * @date 2025/6/30 11:24:04
 */
@Slf4j
@PersistJobDataAfterExecution // 防止创建多个JobDetail，加上注解会重复使用JobDetail
@DisallowConcurrentExecution // 防止并发执行
public class MyJob implements Job {

    @Autowired
    UserService userService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        ObjectMapper objectMapper = new ObjectMapper();

        JobDetail jobDetail = context.getJobDetail();
        log.info("任务名称：{}", jobDetail.getKey().getName());
        log.info("任务分组名字：{}", jobDetail.getKey().getGroup());
        log.info("任务类名字：{}", jobDetail.getJobClass().getName());
        Date fireTime = context.getFireTime();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime fireDateTime = LocalDateTime.ofInstant(fireTime.toInstant(), ZoneId.systemDefault());
        log.info("本次执行时间：{}", fireDateTime.format(formatter));

        // 下次执行时间在once的情况下是获取不到的，为了通用性注释掉
        // Date nextFireTime = context.getNextFireTime();
        // LocalDateTime nextDateTime = LocalDateTime.ofInstant(nextFireTime.toInstant(), ZoneId.systemDefault());
        // log.info("下次执行时间：{}", nextDateTime.format(formatter));

        // 测试数据
//        User user = userService.getByUserId("1864304418397483010");
//        log.info("用户信息：{}", user);
        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        Integer count = (Integer) jobDataMap.get("count");
        log.info("第{}次执行", count);
        jobDataMap.put("count", ++count);
    }
}
